import axios from "axios";
import { useEffect, useState } from "react";
import { DownOutlined, SmileOutlined } from '@ant-design/icons';
import { Table, Radio, Dropdown, message, Button, Modal, Form, Input } from 'antd';
function Goodsorder() {


    const [list, setList] = useState([])
    const [total, setTotal] = useState(0)
    const [pages, setPage] = useState(1)
    const [limits, setlimit] = useState(20)
    const getlist = async () => {
        // console.log("list");
        let { list, total, page, limit } = await axios.get("/store/order/list", {
            params: {
                status: sorder,
                dateLimit,
                orderNo: '',
                page: pages,
                limit: limits,
                type: types,
                temp: new Date().getTime(),
            }
        })
        // console.log(list);
        setList(list)
        setTotal(total)
        setPage(page)
        setlimit(limit)
    }
    //选项卡
    const [types, settype] = useState("2")
    const placementChange = (e) => {//****************************************************************1 */
        console.log(e);
        settype(e.target.value)

    };
    const [sorder, setsorder] = useState("all")
    const placementChange2 = (e) => {//*****************************************************2 */
        // console.log(e.target.value);
        setsorder(e.target.value)

    };
    const [dateLimit, setdateLimit] = useState(" ")
    const placementChange3 = (e) => {//*******************************************************3 */
        // console.log(e);
        setdateLimit(e.target.value)
    };
    //请求
    const [orderNum, setorderNum] = useState("2")
    const gettabfun = async () => {//********************************************************* */
        let res = await axios.get("/store/order/status/num", {
            params: {
                dateLimit,
                type: types,
                temp: new Date().getTime(),
            }
        })
        // console.log(res);
        setorderNum(res)
    }
    //表格
    const columns = [
        {
            title: '订单号',
            dataIndex: 'orderId',
            key: "orderId"
        },
        {
            title: '订单类型',
            dataIndex: 'orderType',
            key: "orderType",
        },
        {
            title: '收货人',
            dataIndex: 'realName',
            key: "realName"
        },

        {
            title: '商品信息',
            dataIndex: 'productScore',
            key: "productScore",
            render: (_, record) => {
                // console.log(record.productList[0].info.productName);
                return (record.productList[0].info.productName)
            }

        },
        {
            title: '实际支付',
            dataIndex: 'payPrice',
            key: "payPrice"
        },
        {
            title: '支付方式',
            dataIndex: 'payTypeStr',
            key: "payTypeStr"
        },
        {
            title: '订单状态',
            dataIndex: 'statusStr',
            key: "statusStr",
            render: (_, record) => {
                // console.log(record.statusStr.value);
                return (record.statusStr.value)
            }
        },
        {
            title: '下单时间',
            dataIndex: 'createTime',
            key: "createTime"
        },
        {
            title: '操作',
            dataIndex: '',
            key: "x",
            render: (_, record) => (<Dropdown
                menu={{
                    items,
                    onClick: downFun,

                }}
            >
                <span onClick={() => moreFun(record)}>

                    更多
                    <DownOutlined />

                </span>
            </Dropdown>)
        },

    ];
    const [isModalOpen, setIsModalOpen] = useState(false);
    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    // 单机更多的时候获取当前一行数据

    const [row, setRow] = useState({})
    const moreFun = async (row) => {//// 更多的单机事件

        let res = await axios.get("/store/order/info", {
            params: {
                orderNo: row.orderId,
                temp: new Date().getTime()
            }
        })
        setRow(res)
    }
    const downFun = (row, b) => {
        console.log(typeof (row.key));

        switch (row.key) {
            case "1":
                showModal()
                break;
            case "2":
                showModal2()
                break;
            case "3":
                showModal3()
                break;


            default:  //  4
                message.info('打印成功');
                break;
        }
        // if (row.key == 4) {
        //     message.info('打印成功');
        // } else if (row.key == 1) {
        //     showModal()
        // } else if (row.key == 2) {
        //     showModal2()
        // } else if (row.key == 3) {
        //     showModal3()
        // }

    }
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const onSelectChange = (newSelectedRowKeys) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
        selections: [
            Table.SELECTION_ALL,
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE,
            {
                key: 'odd',
                text: 'Select Odd Row',
                onSelect: (changeableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return false;
                        }
                        return true;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
            {
                key: 'even',
                text: 'Select Even Row',
                onSelect: (changeableRowKeys) => {
                    let newSelectedRowKeys = [];
                    newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
                        if (index % 2 !== 0) {
                            return true;
                        }
                        return false;
                    });
                    setSelectedRowKeys(newSelectedRowKeys);
                },
            },
        ],
    };
    const onChangePage = (val, b) => {
        console.log(val, b);
        setPage(val)
        setlimit(b)
    }
    const items = [
        {
            key: '1',
            label: (
                <p>
                    订单详情
                </p>
            ),
        },
        {
            key: '2',
            label: (
                <p>
                    订单记录
                </p>
            ),
        },
        {
            key: '3',
            label: (
                <p>
                    订单备注
                </p>
            ),
        },
        {
            key: '4',
            label: (
                <p >
                    打印小票
                </p>
            ),
        },
    ];
    useEffect(() => {
        getlist()
        gettabfun()
        // limits,placement, pages,types,sorder
    }, [types, limits, pages, types, sorder, dateLimit])
    // 第二个弹窗*****************************************************************2********************************
    const [isModalOpen2, setIsModalOpen2] = useState(false);
    const showModal2 = () => {
        setIsModalOpen2(true);
        orderlist(row)

    };
    const handleCancel2 = () => {
        setIsModalOpen2(false);
    };
    const orderlist = async (arg) => {
        console.log(arg);

        let { list, total } = await axios.get("/store/order/status/list", {
            params: {
                page: 1,
                limit: 1000,
                orderNo: arg.orderId,
                temp: new Date().getTime(),
            }
        })
        setdataSource2(list);
        settotal2(total)

    }
    const [dataSource2, setdataSource2] = useState([])
    const [total2, settotal2] = useState(0)
    const columns2 = [
        {
            title: 'ID',
            dataIndex: 'oid',
            key: "oid"
        },
        {
            title: '操作记录',
            dataIndex: 'changeMessage',
            key: "changeMessage",
        },
        {
            title: '操作时间',
            dataIndex: 'createTime',
            key: "createTime"
        },
    ]
    const [pages2, setpages2] = useState()
    const onChangePage2 = () => { }

    // 备注 

    const [isModalOpen3, setIsModalOpen3] = useState(false);
    const showModal3 = () => {
        setIsModalOpen3(true);
        // orderlist(row)

    };
    const handleCancel3 = () => {
        setIsModalOpen3(false);
    };


    // 下面是表单
    const onFinish = async (values) => {
        // console.log('Success:', values);
        let res = await axios.post(`/store/order/mark?mark=${values.mark}&orderNo=${row.orderId}`)
        setIsModalOpen3(false);
        getlist()
        form.resetFields();
    };
    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    const [textArea, setTextArea] = useState("")
    const [form] = Form.useForm();
    const onReset = () => {
        form.resetFields();
    };
    return (
        <div className="whitebg">
            商品订单

            <div>
                <span style={{ fontSize: "25px", }}>订单类型:</span>
                {/* 选项卡 */}
                <Radio.Group value={types} onChange={placementChange}>
                    <Radio.Button value="2">全部</Radio.Button>
                    <Radio.Button value="0">普通订单</Radio.Button>
                    <Radio.Button value="1">视频号订单</Radio.Button>
                </Radio.Group>

            </div>
            <div>
                <span style={{ fontSize: "25px", }}>订单状态:</span>
                {/* 选项卡 */}
                <Radio.Group value={sorder} onChange={placementChange2}>
                    <Radio.Button value="all">全部{orderNum.all}</Radio.Button>
                    <Radio.Button value="unPaid">未支付{orderNum.unPaid}</Radio.Button>
                    <Radio.Button value="notShipped">未发货{orderNum.notShipped}</Radio.Button>
                    <Radio.Button value="spike">待收货{orderNum.spike}</Radio.Button>
                    <Radio.Button value="bargain">待评价{orderNum.bargain}</Radio.Button>
                    <Radio.Button value="complete">交易完成{orderNum.complete}</Radio.Button>
                    <Radio.Button value="toBeWrittenOff">待核销{orderNum.toBeWrittenOff}</Radio.Button>
                    <Radio.Button value="refunding">退款中{orderNum.refunding}</Radio.Button>
                    <Radio.Button value="refunded">已退款{orderNum.refunded}</Radio.Button>
                    <Radio.Button value="deleted">已删除{orderNum.deleted}</Radio.Button>
                </Radio.Group>

            </div>
            <div>
                <span style={{ fontSize: "25px", }}>时间选择:</span>
                {/* 选项卡 */}
                <Radio.Group value={dateLimit} onChange={placementChange3}>
                    <Radio.Button value=" ">全部</Radio.Button>
                    <Radio.Button value="today">今天</Radio.Button>
                    <Radio.Button value="yesterday">昨天</Radio.Button>
                    <Radio.Button value="lately7">最近7天</Radio.Button>
                    <Radio.Button value="lately30">最近30天</Radio.Button>
                    <Radio.Button value="month">本月</Radio.Button>
                    <Radio.Button value="year">本年</Radio.Button>
                </Radio.Group>

            </div>

            {/* 表格 */}
            <Table columns={columns} dataSource={list}
                rowSelection={rowSelection}

                rowKey="orderId"
                pagination={{
                    defaultCurrent: pages,

                    pageSize: limits,
                    total: 100,
                    onChange: onChangePage
                }}

            />
            <div>
                <Modal title="订单详情" open={isModalOpen} footer={null} onCancel={handleCancel}>
                    <h4>用户信息</h4>
                    用户昵称：{row.nikeName}
                    绑定电话：{row.userPhone}
                    <h4>收获信息</h4>
                    收货人：{row.realName}
                    收货电话：{row.userPhone}
                    收货地址{row.userAddress}

                    <h4>订单信息</h4>
                    订单编号：{row.orderId}
                    订单状态:{row.statusStr ? row.statusStr.value : " "}
                    商品总数：{row.totalNum}
                    商品总价：{row.proTotalPrice}
                    支付邮费：{row.proTotalPrice}
                    优惠券金额：{row.couponPrice}
                    实际支付：{row.payPrice}
                    抵扣金额：{row.deductionPrice}
                    退款金额：{row.refundPrice}
                    创建时间：{row.createTime}
                    支付方式：{row.payTypeStr}
                    推广人：- {row.spreadName}
                    商家备注：{row.remark}
                </Modal>
            </div>
            <div>
                <Modal title="订单详情" open={isModalOpen2} footer={null} onCancel={handleCancel2}>
                    <Table columns={columns2} dataSource={dataSource2}


                        rowKey="oid"
                        pagination={{
                            defaultCurrent: pages2,
                            pageSize: 10,

                            total: total2,
                            // pageSizeOptions:[10,20,30,50,100]
                            onChange: onChangePage2
                        }}

                    />
                </Modal>
            </div>
            <div>
                <Modal title="订单详情" open={isModalOpen3} footer={null} onCancel={handleCancel3}>
                    <Form
                        name="basic"
                        form={form}
                        labelCol={{
                            span: 8,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                        style={{
                            maxWidth: 600,
                        }}
                        initialValues={{
                            remember: true,
                        }}
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="订单备注"
                            name="mark"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入订单备注!',
                                },
                            ]}
                        >
                            <Input.TextArea value={textArea} onChange={(e) => setTextArea(e.target.value)} />
                        </Form.Item>




                        <Form.Item
                            wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}
                        >
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                            <Button htmlType="button" onClick={onReset}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        </div>
    );
}

export default Goodsorder;